<template>
  <div class="health-check-chart">
    <h3>{{ title }}</h3>
    <div v-if="loading" class="chart-loading">
      <el-skeleton :rows="6" animated />
    </div>
    <div v-else-if="noData" class="no-data">
      <el-empty description="暂无数据" />
    </div>
    <div v-else class="chart-container" ref="chartRef"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import * as echarts from 'echarts/core'
import { LineChart, BarChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必要的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  LineChart,
  BarChart,
  PieChart,
  CanvasRenderer
])

const props = defineProps({
  type: {
    type: String,
    default: 'line',
    validator: value => ['line', 'bar', 'pie'].includes(value)
  },
  title: {
    type: String,
    default: '健康数据统计'
  },
  data: {
    type: Array,
    default: () => []
  },
  xField: {
    type: String,
    default: 'date'
  },
  yField: {
    type: String,
    default: 'value'
  },
  loading: {
    type: Boolean,
    default: false
  }
})

const chartRef = ref(null)
let chartInstance = null

const noData = computed(() => !props.data || props.data.length === 0)

const initChart = () => {
  if (!chartRef.value) return
  
  // 如果实例已存在则销毁
  if (chartInstance) {
    chartInstance.dispose()
  }
  
  // 创建新的图表实例
  chartInstance = echarts.init(chartRef.value)
  
  // 根据类型生成不同图表
  const option = getChartOption()
  chartInstance.setOption(option)
}

const getChartOption = () => {
  const baseOption = {
    title: {
      text: props.title,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      bottom: '5%'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    }
  }
  
  // 根据图表类型返回不同配置
  switch (props.type) {
    case 'line':
      return {
        ...baseOption,
        xAxis: {
          type: 'category',
          data: props.data.map(item => item[props.xField])
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          name: props.title,
          type: 'line',
          data: props.data.map(item => item[props.yField]),
          smooth: true,
          symbolSize: 6,
          itemStyle: {
            color: '#409EFF'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: 'rgba(64, 158, 255, 0.6)'
              }, {
                offset: 1, color: 'rgba(64, 158, 255, 0.1)'
              }]
            }
          }
        }]
      }
    case 'bar':
      return {
        ...baseOption,
        xAxis: {
          type: 'category',
          data: props.data.map(item => item[props.xField])
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          name: props.title,
          type: 'bar',
          data: props.data.map(item => item[props.yField]),
          barWidth: '50%',
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: '#67C23A'
              }, {
                offset: 1, color: '#95D475'
              }]
            },
            borderRadius: [4, 4, 0, 0]
          }
        }]
      }
    case 'pie':
      return {
        ...baseOption,
        series: [{
          name: props.title,
          type: 'pie',
          radius: ['40%', '70%'],
          center: ['50%', '50%'],
          data: props.data.map(item => ({
            name: item[props.xField],
            value: item[props.yField]
          })),
          itemStyle: {
            borderRadius: 6,
            borderWidth: 2,
            borderColor: '#fff'
          },
          label: {
            formatter: '{b}: {c} ({d}%)'
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }
    default:
      return baseOption
  }
}

// 监听数据变化重新渲染图表
watch(() => props.data, () => {
  if (!noData.value) {
    initChart()
  }
}, { deep: true })

// 窗口大小变化时重新调整图表大小
window.addEventListener('resize', () => {
  if (chartInstance) {
    chartInstance.resize()
  }
})

onMounted(() => {
  if (!noData.value) {
    initChart()
  }
})
</script>

<style scoped>
.health-check-chart {
  width: 100%;
  margin-bottom: 20px;
}

.chart-container {
  width: 100%;
  height: 350px;
}

.chart-loading, .no-data {
  height: 350px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style> 